import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
// SocketChannel 相当于 socket 编程的 socket , 用于创建客户端通道
public class SocketChannelDemo {
    private static final int MAX_SIZE = 1024;
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("www.baidu.com", 80));
        socketChannel.configureBlocking(false);   //设置非阻塞模式
        ByteBuffer buffer = ByteBuffer.allocate(MAX_SIZE);
        int len = socketChannel.read(buffer);
        byte[] bys = new byte[len];
        for (int i = 0; i < len; i++) {
            bys[i] = buffer.get(i);
        }
        System.out.println(new String(bys,0,len));
        socketChannel.close();
    }
}
